"""
File   : 01_2_chat_stream.py
Desc   : 对话补全流式输出
Date   : 2024/11/27
Author : Tianyu Chen
"""


from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {
            "role": "system", 
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Who are you"
        }
    ],
    stream=True  # 开启流式访问
)

for chunk in completion:
    print(chunk.choices[0].delta.content)
""" output:

I
 am
 an
 artificial
 intelligence
 developed
 by
 Open
AI
,
 designed
 to
 assist
 users
 by
 answering
 questions
 and
 providing
 information
 on
 a
 wide
 range
 of
 topics
.
 How
 can
 I
 help
 you
 today
?
None
""" 

# for chunk in completion:
#     print(chunk)
"""
ChatCompletionChunk(
    id='chatcmpl-AQ58by6BbpUGgYWJarmGFeiKsPfaw', 
    choices=[
        Choice(
            delta=ChoiceDelta(
                content='I', 
                function_call=None, 
                refusal=None, 
                role='assistant', 
                tool_calls=None
            ), 
            finish_reason=None, 
            index=0, 
            logprobs=None
        )
    ], 
    created=1730779641, 
    model='gpt-4o-mini-2024-07-18', 
    object='chat.completion.chunk', 
    service_tier=None, 
    system_fingerprint='fp_0ba0d124f1', 
    usage=None
)
...
"""